package logic

import (
	"context"
	"fmt"
	"jd/model/mysql"
	"jd/model/redis"
	"jd/pkg"

	"jd/userrpc/internal/svc"
	"jd/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *userrpc.UserLoginRequest) (*userrpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line

	get := redis.Rdb.Get("sendSmslogin" + in.Tel)

	if get.Val() == "" {
		return nil, fmt.Errorf("暂未获取短信验证码")
	}
	if get.Val() != in.SendSmsCode {
		return nil, fmt.Errorf("短信验证码输入错误")
	}

	var user mysql.User

	err := mysql.DB.Debug().Model(&mysql.User{}).Where("tel=?", in.Tel).First(&user).Error
	if err != nil {
		return nil, fmt.Errorf("改用户不存在")
	}
	password1 := pkg.Md5(in.Password)
	if user.Password != password1 {
		return nil, fmt.Errorf("密码错误")
	}

	redis.Rdb.Del("sendSmslogin" + in.Tel)
	
	return &userrpc.UserLoginResponse{Id: int64(user.ID)}, nil
}
